﻿using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Threading;
using Data;
using Entities;
using WebLog;
namespace Logic
{
    public sealed class VoterLogic
    {

        internal Location GetLocationFromIP(string ipAddress, string path)
        {
            try
            {
                LookupService service = new LookupService(path);
                Location loc = service.getLocation(ipAddress);

                return loc;
            }
            catch (Exception e)
            {
                Logger logger = Logger.GetInstance;
                logger.WriteLog(e);
                return null;
            }
        }

        public bool ValidateCaptcha(string userCode, string captchaCode)
        {
            userCode = userCode.CleanParameter<string>();
            if (userCode.ValidateText(5) && captchaCode != null)
            {
                if (userCode.ToLower() == captchaCode.ToLower())
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            else
            {
                return false;
            }

        }

        public bool FindVoterByEmailLogic(string email)
        {
            email = email.CleanParameter<string>();
            if (email.Length <= 50)
            {
                return new VoterData().FindVoterByEmail(email);
            }
            else
            {
                return false;
            }
        }

        public bool InsertVoterLogic(Voter i, string key, string userMail, string passwordMail, string mailServer)
        {
            bool response = false;

            //preuba
          
            i.name = i.name.CleanParameter<string>();
            i.middleName = i.middleName.CleanParameter<string>();
            i.lastName = i.lastName.CleanParameter<string>();
            i.secondLastName = i.secondLastName.CleanParameter<string>();
            i.email = i.email.CleanParameter<string>();
            i.address = i.address.CleanParameter<string>();
            i.smallTown = i.smallTown.CleanParameter<string>();
            i.regionId = i.regionId.CleanParameter<string>();
            i.communeId = i.communeId.CleanParameter<string>();
            i.telephone = i.telephone.CleanParameter<string>();
            i.cellPhone = i.cellPhone.CleanParameter<string>();

            //desencriptar los id
            i.civilStatus = Encryption.DecryptData(i.civilStatus, key);
            i.sex = Encryption.DecryptData(i.sex, key);


            i.sex = i.sex.CleanParameter<string>();
            i.civilStatus = i.civilStatus.CleanParameter<string>();
            
            // i.sex = null;  funciona !!! =) si es null no se cae ...


            if (i.name.ValidateText(30) && i.middleName.ValidateText(30) && i.lastName.ValidateText(30) && i.secondLastName.ValidateText(30) && i.birthDate.ValidateDate() &&
                i.email.ValidateMail(50) && i.address.ValidateAddress(56) && i.smallTown.ValidateAddress(40) && i.regionId.IsNumber() /*&& i.region.ValidateRegion(50) && i.comuna.ValidateRegion(50)*/ && i.telephone.ValidateTelephone(9)
                && i.cellPhone.ValidateTelephone(9) && i.group != null && i.sex.IsNumber() && i.civilStatus.IsNumber() && i.communeId.IsNumber() && i.civilStatus.IsNumber())
            {
                VoterData voter = new VoterData();
                string descryptPass = Password.Generate(i);
                i.password = Encryption.EncriptData(descryptPass, key);
                response = voter.InsertVoter(i);

                if (response)
                {

                    Thread theadEmail = new Thread(delegate() { Mail.SendMail(i.email, StringBuilderFunctions.JoinString(i.name, " ", i.lastName, " ", "su contraseña es:", " ", descryptPass), "Contraseña sistema votacion", userMail, passwordMail, mailServer, null); });
                    theadEmail.IsBackground = true;
                    theadEmail.Start();

                }
            }

            return response;
        }

        public bool SearchVoterByIdLogic(Voter i)
        {
            i.rut = i.rut.CleanParameter<string>();
            if (i.rut.ValidateRut())
            {
                VoterData voter = new VoterData();
                bool response = voter.SearchVoterById(i);
                return response;
            }
            else
            {
                return true;
            }

        }

        public Voter GetVoterLogic(string rut, string password, string ip, string browser, string key, string dataBasePath)
        {
            rut = rut.CleanParameter<string>();
            password = password.CleanParameter<string>();
            if (rut.ValidateRut() && password.ValidatePassword())
            {
                password = Encryption.EncriptData(password, key);
                VoterData vc = new VoterData();
                string cuerpo = rut.Substring(0, rut.Length - 1);
                string digito = rut.Substring(rut.Length - 1, 1);

                Voter response = vc.GetVoter(cuerpo, digito, password);
                if (response != null)
                {
                    response.register.ipLastLogin = ip;
                    response.register.browser = browser;

                    Location loc = GetLocationFromIP(ip, dataBasePath);

                    if (loc != null)
                    {
                        response.register.city = loc.city;
                        response.register.country = loc.countryName;
                        response.register.region = loc.regionName;
                        vc.InsertVoterRegister(response);
                        return response;

                    }
                    else
                    {
                        response.register.city = "N/D";
                        response.register.country = "N/D";
                        response.register.region = "N/D";
                        vc.InsertVoterRegister(response);
                        return response;

                    }

                }
                else
                {
                    return response;
                }
            }
            else
            {
                return null;
            }
        }

        public void GeneratePdfLogic(Voter vc)
        {
            PDF.Generate(vc);
        }

        public string GeneratePasswordPdf()
        {
            return Password.GenerateIdPdf();
        }

        public void SendEmailLogic(Voter vc, string message, string userMail, string passwordMail, string mailServer, string attached)
        {
            Thread threadEmail = new Thread(delegate() { Mail.SendMail(vc.email, StringBuilderFunctions.JoinString("Sr. o Sra.", " ", vc.GetFullName(), message), "Mensaje Administrador", userMail, passwordMail, mailServer, attached); });
            threadEmail.IsBackground = true;
            threadEmail.Start();
        }

        public string EncryptDataLogic(string data, string key)
        {
            return Encryption.EncriptData(data, key);
        }

        public string DecryptDataLogic(string data, string key)
        {
            return Encryption.DecryptData(data, key);
        }

        public List<Voter> GetListVoters(string key)
        {
            VoterData vd = new VoterData();
            List<Voter> encryptList = new List<Voter>();
            List<Voter> listaDb = vd.GetListVoters();
            if (listaDb != null)
            {
                foreach (Voter cc in listaDb)
                {
                    cc.id = Encryption.EncriptData(cc.id.ToString(), key);
                    encryptList.Add(cc);
                }

                return encryptList;
            }
            else
            {
                return null;
            }
        }

        public List<Voter> SearchVoterByRutLogic(string rut, string key)
        {
            rut = rut.CleanParameter<string>();
            if (rut.ValidateRut())
            {
                List<Voter> response = new VoterData().SearchVoterByRut(rut);
                if (response != null)
                {
                    foreach (Voter cc in response)
                    {
                        cc.id = Encryption.EncriptData(cc.id.ToString(), key);

                    }

                    return response;
                }
                else
                {
                    return null;
                }

            }
            else
            {
                return null;
            }

        }

        public List<Voter> SearchVoterByName(string name, string key)
        {
            name = name.CleanParameter<string>();
            if (name.ValidateText(30))
            {
                List<Voter> response = new VoterData().SearchVoterByName(name);
                if (response != null)
                {
                    foreach (Voter cc in response)
                    {
                        cc.id = Encryption.EncriptData(cc.id.ToString(), key);

                    }

                    return response;
                }
                else
                {
                    return null;
                }
            }
            else
            {
                return null;
            }

        }

        public List<Voter> SearchVoterByLastNameLogic(string lastName, string key)
        {
            lastName = lastName.CleanParameter<string>();
            if (lastName.ValidateText(30))
            {
                List<Voter> response = new VoterData().SearchVoterByLastName(lastName);
                if (response != null)
                {
                    foreach (Voter cc in response)
                    {
                        cc.id = Encryption.EncriptData(cc.id.ToString(), key);

                    }

                    return response;
                }
                else
                {
                    return null;
                }
            }
            else
            {
                return null;
            }

        }

        public List<Voter> SearchVoterByEmailLogic(string email, string key)
        {
            email = email.CleanParameter<string>();
            if (email.ValidateMail(50))
            {
                List<Voter> response = new VoterData().SearchVoterByEmail(email);
                if (response != null)
                {
                    foreach (Voter cc in response)
                    {
                        cc.id = Encryption.EncriptData(cc.id.ToString(), key);

                    }

                    return response;
                }
                else
                {
                    return null;
                }
            }
            else
            {
                return null;
            }

        }

        public List<Voter> SearchVoterByTelephoneLogic(string telephone, string key)
        {
            telephone = telephone.CleanParameter<string>();
            if (telephone.ValidateTelephone(9))
            {
                List<Voter> response = new VoterData().SearchVoterByTelephone(telephone);
                if (response != null)
                {
                    foreach (Voter cc in response)
                    {
                        cc.id = Encryption.EncriptData(cc.id.ToString(), key);

                    }

                    return response;
                }
                else
                {
                    return null;
                }
            }
            else
            {
                return null;
            }

        }

        public List<Voter> SearchVoterByCellphoneLogic(string cellphone, string key)
        {
            cellphone = cellphone.CleanParameter<string>();
            if (cellphone.ValidateTelephone(9))
            {
                List<Voter> response = new VoterData().SearchVoterByCellphone(cellphone);
                if (response != null)
                {
                    foreach (Voter cc in response)
                    {
                        cc.id = Encryption.EncriptData(cc.id.ToString(), key);

                    }

                    return response;
                }
                else
                {
                    return null;
                }
            }
            else
            {
                return null;
            }

        }

        public List<Voter> SearchVoterByDateLogic(DateTime date, string key)
        {
            date = date.CleanParameter<DateTime>();
            if (date.ValidateDate())
            {
                List<Voter> response = new VoterData().SearchVoterByDate(date);
                if (response != null)
                {
                    foreach (Voter cc in response)
                    {
                        cc.id = Encryption.EncriptData(cc.id.ToString(), key);

                    }

                    return response;
                }
                else
                {
                    return null;
                }
            }
            else
            {
                return null;
            }

        }

        public List<Voter> SearchVoterByBlockedLogic(string blocked, string key)
        {
            bool resp;
            blocked = blocked.CleanParameter<string>();
            if (blocked.ValidateText(2))
            {
                if (blocked.ToLower() == "si")
                {
                    resp = true;
                }
                else
                {
                    resp = false;
                }
                List<Voter> response = new VoterData().SearchVoterByBlocked(resp);
                if (response != null)
                {
                    foreach (Voter cc in response)
                    {
                        cc.id = Encryption.EncriptData(cc.id.ToString(), key);
                    }

                    return response;
                }
                else
                {
                    return null;
                }
            }
            else
            {
                return null;
            }

        }

        public List<string> AutocompleteByNameLogic(string name)
        {
            name = name.CleanParameter<string>();
            if (name.ValidateText(30))
            {
                List<string> response = new VoterData().AutocompleteByName(name);
                return response;
            }
            else
            {
                return null;
            }
        }

        public List<string> AutocompleteByLastNameLogic(string lastName)
        {
            lastName = lastName.CleanParameter<string>();
            if (lastName.ValidateText(30))
            {
                List<string> response = new VoterData().AutocompleteByLastName(lastName);
                return response;
            }
            else
            {
                return null;
            }
        }

        public List<string> AutocompleteByEmailLogic(string email)
        {
            email = email.CleanParameter<string>();
            if (email.Length <= 50)
            {
                List<string> response = new VoterData().AutocompleteByEmail(email);
                return response;
            }
            else
            {
                return null;
            }
        }

        public List<string> AutocompleteByRutLogic(string rut)
        {
            rut = rut.CleanParameter<string>();
            if (!string.IsNullOrWhiteSpace(rut) && rut.Length <= 9)
            {
                List<string> response = new VoterData().AutocompleteByRut(rut);
                if (response != null)
                {
                    return response;
                }
                else
                {
                    return null;
                }
            }
            else
            {
                return null;
            }
        }

        public bool UpgradeVoterLogic(Voter i)
        {
            bool response = false;
            i.name = i.name.CleanParameter<string>();
            i.lastName = i.lastName.CleanParameter<string>();
            i.email = i.email.CleanParameter<string>();
            i.id = i.id.CleanParameter<string>();
            i.cellPhone = i.cellPhone.CleanParameter<string>();
            i.secondLastName = i.secondLastName.CleanParameter<string>();
            i.middleName = i.middleName.CleanParameter<string>();
            i.telephone = i.telephone.CleanParameter<string>();
            i.birthDate = i.birthDate.CleanParameter<DateTime>();
            i.address = i.address.CleanParameter<string>();
            i.smallTown = i.smallTown.CleanParameter<string>();
            i.regionId = i.regionId.CleanParameter<string>();

            if (i.name.ValidateText(30) && i.lastName.ValidateText(30) && i.middleName.ValidateText(30) && i.secondLastName.ValidateText(30) &&
               i.email.ValidateMail(50) && i.telephone.ValidateTelephone(9) && i.cellPhone.ValidateTelephone(9) && i.id.ToString().IsNumber()
                && i.birthDate.ValidateDate() && i.address.ValidateAddress(56) && i.smallTown.ValidateAddress(40) && i.regionId.IsNumber() && i.votingList != null)
            {
                response = new VoterData().UpgradeVoter(i);
            }
            return response;

        }

        public bool DeleteVoterLogic(string id, string key)
        {
            bool response = false;
            id = Encryption.DecryptData(id, key);
            id = id.CleanParameter<string>();

            if (id.IsNumber())
            {
                response = new VoterData().DeleteVoter(Convert.ToInt32(id));
            }
            return response;
        }

        public bool ChangeVoterPasswordLogic(Voter i, string userMail, string passwordMail, string mailServer)
        {
            string password = Password.Generate(i);
            i.password = password;
            if (new VoterData().ChangeVoterPassword(i))
            {
                Thread threadEmail = new Thread(delegate() { Mail.SendMail(i.email, StringBuilderFunctions.JoinString(i.name, " ", i.lastName, " ", "Su nueva password es: ", password), "Cambio Password", userMail, passwordMail, mailServer, null); });
                threadEmail.IsBackground = true;
                threadEmail.Start();
                return true;
            }
            else
            {
                return false;
            }

        }

        public Voter GetVoterById(string id, string key)
        {
            id = Encryption.DecryptData(id, key);
            id = id.CleanParameter<string>();

            if (id.IsNumber())
            {
                return new VoterData().GetVoterById(Convert.ToInt32(id));
            }
            else
            {
                return null;
            }
        }

        public string FirstLetterToUppercaseLogica(string word)
        {
            return word.FirstToUpper();
        }

        public string JoinStringLogic(params string[] data)
        {
            return StringBuilderFunctions.JoinString(data);
        }

        public bool UpgradeVoterPictureLogic(Voter i)
        {
            if (i.voterPicture.ValidatePicture())
            {
                return new VoterData().UpgradeVoterPicture(i);
            }
            else
            {
                return false;
            }
        }

        public string DecryptDataVoterIdLogic(string id, string key)
        {
            return Encryption.DecryptData(id, key);
        }

        public string UpdateVoterPasswordLogic(Voter i, string oldPassword, string newPassword, string newPasswordRepet, string key, string mail_server, string user_password, string user_mail)
        {
            VoterData voterData = new VoterData();
            string response = string.Empty;

            oldPassword = oldPassword.CleanParameter<string>();
            newPassword = newPassword.CleanParameter<string>();
            newPasswordRepet = newPasswordRepet.CleanParameter<string>();


            if (newPassword.ValidateNewPassword() && newPasswordRepet.ValidateNewPassword())
            {
                if (newPassword == newPasswordRepet)
                {
                    if (oldPassword.ValidatePassword())
                    {
                        oldPassword = EncryptDataLogic(oldPassword, key);
                        if (oldPassword != null && voterData.CheckVoterOldPassword(i, oldPassword))
                        {
                            string passTemp = newPassword;
                            newPassword = EncryptDataLogic(newPassword, key);

                            if (voterData.UpdateVoterPassword(i, newPassword))
                            {
                                response = "Contraseña cambiada";

                                SendEmailLogic(i, "Su nueva contraseña es : " + passTemp, user_mail, user_password, mail_server, null);
                                return response;
                            }
                            else
                            {
                                response = "Problema al actualizar la contraseña.Intente mas tarde";
                                return response;
                            }

                        }
                        else
                        {
                            response = "Password antigua no valida";
                            return response;
                        }
                    }
                    else
                    {
                        response = "Password antigua no valida";
                        return response;
                    }

                }
                else
                {
                    response = "Password nueva valida";
                    return response;
                }
            }
            else
            {
                response = "Password nueva valida";
                return response;
            }









        }

        public List<string> GetListVoterRegisterLogic(string id)
        {
            List<Register> list = new VoterData().GetListVoterRegister(Convert.ToInt32(id));
            List<string> listRegister = new List<string>();
            if (list != null)
            {
                foreach (Register r in list)
                {
                    listRegister.Add(JoinStringLogic(r.dateLastLoginView, " a las ", r.hourLastLogin, " - ", r.city, ",", r.region, ",", r.country, ",", " a través de ", r.browser));
                }

                return listRegister;
            }
            else
            {
                return null;
            }
        }

        public List<CivilStatus> GetListCivilStatusLogic(string key)
        {
            List<CivilStatus> list = new VoterData().GetListCivilStatus();

            if (list != null)
            {

                foreach (CivilStatus cv in list)
                {
                    cv.id = EncryptDataLogic(cv.id, key);
                }
                return list;
            }
            else
            {
                return null;
            }
        }

        public List<Gender> GetListSexLogic(string key)
        {
            List<Gender> list = new VoterData().GetListSex();

            if (list != null)
            {

                foreach (Gender cv in list)
                {
                    cv.id = EncryptDataLogic(cv.id, key);
                }
                return list;
            }
            else
            {
                return null;
            }
        }

        public List<Entities.Group> GetListGroupLogic(string key)
        {
            List<Entities.Group> list = new VoterData().GetlistOfGroup();

            if (list != null)
            {

                foreach (Entities.Group cv in list)
                {
                    cv.id = EncryptDataLogic(cv.id, key);
                }
                return list;
            }
            else
            {
                return null;
            }
        }


        public Entities.Group GetGroupByIdLogic(string key, string id)
        {
            string dc = Encryption.DecryptData(id, key);

            if (dc != null && dc.IsNumber())
            {
                Entities.Group v = new VoterData().GetGroupById(dc);

                if (v != null)
                {
                    return v;
                }
                else
                {
                    return null;
                }

            }
            else
            {
                return null;
            }
        }
    }
}
